import 'package:flame/components.dart';
import 'package:flutter/material.dart';
import 'package:flutter_flame/config/GameConfig.dart';

import '../../../config/GameColors.dart';

// 血条
class HealthBar extends PositionComponent with GameConfig {
  final double maxHealth; // 最大生命值
  double _currentHealth; // 当前血量
  final double healthBarWidth; // 血条的宽度
  final double healthBarHeight; // 血条的高度
  final double healthBarLeft; // 左侧距离
  final double healthBarTop; // 顶部距离
  final Color backgroundColor; // 背景颜色
  final double borderWidth = 1; // 边宽

  late Paint _bgPaint;
  late Paint _fgPaint;
  late Rect _bgRect;
  late Rect _fgRect;
  double _percent = 1.0;

  double get currentHealth => _currentHealth;

  set currentHealth(double value) {
    _currentHealth = value.clamp(0, maxHealth);
    _percent = (_currentHealth / maxHealth).clamp(0.0, 1.0);
    _fgPaint = Paint();
    _getHealthColor(_percent);
    _fgRect = Rect.fromLTWH(
      borderWidth + healthBarLeft,
      borderWidth + healthBarTop,
      healthBarWidth * _percent - borderWidth * 2,
      healthBarHeight - borderWidth * 2,
    );
  }

  HealthBar({
    required this.maxHealth,
    required double currentHealth,
    this.backgroundColor = GameColors.healthBarBackgroundColor,
    this.healthBarWidth = 50.0,
    this.healthBarHeight = 5.0,
    this.healthBarLeft = 40.0,
    this.healthBarTop = 40.0,
  }) : _currentHealth = currentHealth {
    _bgPaint = Paint()..color = backgroundColor;
    _fgPaint = Paint();
    _bgRect = Rect.fromLTWH(
      healthBarLeft,
      healthBarTop,
      healthBarWidth,
      healthBarHeight,
    );
    this.currentHealth = currentHealth;
  }

  @override
  void update(double dt) {
    if (_currentHealth <= 0) removeFromParent();
    super.update(dt);
  }

  @override
  void render(Canvas canvas) {
    canvas.drawRect(_bgRect, _bgPaint);
    canvas.drawRect(_fgRect, _fgPaint);
  }

  void _getHealthColor(double percent) {
    if (_percent >= 0.9) {
      _fgPaint.color = GameColors.healthBarStep1BackgroundColor;
    } else if (_percent >= 0.7) {
      _fgPaint.color = GameColors.healthBarStep2BackgroundColor;
    } else if (_percent >= 0.5) {
      _fgPaint.color = GameColors.healthBarStep3BackgroundColor;
    } else if (_percent >= 0.3) {
      _fgPaint.color = GameColors.healthBarStep4BackgroundColor;
    } else {
      _fgPaint.color = GameColors.healthBarStep5BackgroundColor;
    }
  }
}
